package com.zxy.ziems.server.foms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxy.ziems.server.foms.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class FomsRpcService extends BaseRpcService {

    private final String id = "foms";

    @Value("${zifoms-server.url}")
    private String zifomsServerAddr;
    @Value("${zifoms-server.tenant-id}")
    private String zifomsTenantId;

    private final Long expire = 60L;

    private final Logger logger = LoggerFactory.getLogger(FomsRpcService.class);

    @Override
    public String getBaseUrl() {
        return zifomsServerAddr;
    }

    public UserInfo detail(String userId, String tenantId) {
        String url = buildUrl("/rpc/user/info/detail");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("tenantId", tenantId);
        String key = userId.concat(tenantId);
        UserInfo userInfo = (UserInfo) this.getRedisCache(this.id, key);
        if (userInfo == null) {
            String response = requestData(url, params);
            userInfo = JSONObject.parseObject(response, UserInfo.class);
            this.setRedisCache(this.id, key, userInfo, expire);
        }
        return userInfo;
    }

    public UserInfo detail(String userId, Integer status, String tenantId) {
        String url = buildUrl("/rpc/user/info/detail");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("status", status);
        params.put("tenantId", tenantId);
//        params.put("deptIds", MyUserUtil.getDeptIds());
        String key = userId.concat(status.toString()).concat(tenantId);
        UserInfo userInfo = (UserInfo) this.getRedisCache(this.id, key);
        if (userInfo == null) {
            String response = requestData(url, params);
            userInfo = JSONObject.parseObject(response, UserInfo.class);
            this.setRedisCache(this.id, key, userInfo, expire);
        }
        return userInfo;
    }

    public List<UserInfo> batchDetail(Set<String> userIds) {
        String url = buildUrl("/rpc/user/info/batchDetail");
        Map<String, Object> params = new HashMap<>();
        params.put("userIds", userIds);
        params.put("tenantId", zifomsTenantId);
        String response = requestData(url, params);
        List<UserInfo> userInfo = JSONObject.parseArray(response, UserInfo.class);
        return userInfo;
    }

    public TenantUser loadByUserId(String userId, String tenantId) {
        String url = buildUrl("/rpc/tenant/user/info");
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("userId", userId);
        String response = requestData(url, params);
        return JSON.parseObject(response, TenantUser.class);
    }

    public UserInfo loginUserInfo(String userId, String tenantId) {
        UserInfo userInfo = null;
        String url = buildUrl("/rpc/user/login/info");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("tenantId", tenantId);
//        params.put("deptIds", MyUserUtil.getDeptIds());
        String key = userId.concat(tenantId).concat("loginInfo");
        try {
            userInfo = (UserInfo) this.getRedisCache(this.id, key);
        } catch (Exception ignored) {
            userInfo = null;
        }

        if (userInfo == null) {
            String response = requestData(url, params);
            userInfo = JSONObject.parseObject(response, UserInfo.class);
            this.setRedisCache(this.id, key, userInfo, expire);
        }
        return userInfo;
    }

    public UserInfo getUserInfo(String userId) {
        String url = buildUrl("/rpc/user/info/getUserInfo");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("tenantId", zifomsTenantId);
        String response = requestData(url, params);
        UserInfo userInfo = JSONObject.parseObject(response, UserInfo.class);
        return userInfo;
    }


    public IPage<UserInfo> pageList(UserQparams queryParams) {
        String url = buildUrl("/rpc/user/info/page");

        Map<String, Object> params = new HashMap<>();
        params.put("deptId", queryParams.getDeptId());
        params.put("pageNo", queryParams.getPageNo());
        params.put("pageSize", queryParams.getPageSize());
        params.put("name", queryParams.getName());
        params.put("phone", queryParams.getPhone());
        params.put("tenantId", zifomsTenantId);

        String response = requestData(url, params);
        Map<String, Object> map = JSONObject.parseObject(response, Map.class);
        List<UserInfo> records = JSONObject.parseArray(JSONObject.toJSONString(map.get("records")), UserInfo.class);

        Page<UserInfo> userInfoPage = new Page<>();
        userInfoPage.setRecords(records);
        userInfoPage.setTotal(MapUtils.getLong(map, "total"));
        userInfoPage.setPages(MapUtils.getLong(map, "pages"));
        userInfoPage.setSize(MapUtils.getLong(map, "size"));
        userInfoPage.setCurrent(MapUtils.getLong(map, "current"));

        return userInfoPage;
    }

    public List<DeptInfoTree> deptTree(String currentId, String tenantId, List<String> deptIds) {
        String url = buildUrl("/rpc/dept/info/tree");
        Map<String, Object> params = new HashMap<>();
        params.put("currentId", currentId);
        params.put("tenantId", tenantId);
        params.put("deptIds", deptIds);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, DeptInfoTree.class);
    }

    /**
     * 获取当前部门内的人员信息
     *
     * @param deptId
     * @param tenantId
     * @return
     */
    public List<UserInfo> listUserByDeptId(String deptId, String tenantId) {
        String url = buildUrl("/rpc/dept/getUsers");
        Map<String, Object> params = new HashMap<>();
        params.put("id", deptId);
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, UserInfo.class);
    }

    public List<DeptInfoTree> pullUserTree(String currentId, String tenantId) {
        String url = buildUrl("/rpc/dept/user/tree");
        Map<String, Object> params = new HashMap<>();
        params.put("currentId", currentId);
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, DeptInfoTree.class);
    }

    public List<DeptTreeVo> flowDeptTreeAll(String tenantId) {
        String url = buildUrl("/rpc/flow/dept/info/myTree");
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, DeptTreeVo.class);
    }

    public List<DeptInfo> listAllDept(String tenantId) {
        String url = buildUrl("/rpc/dept/info/listAll");
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, DeptInfo.class);
    }

    public DeptInfo loadDeptById(String id) {
        String url = buildUrl("/rpc/dept/info/detail");
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        DeptInfo deptInfo = null;
        String key = id.concat("deptInfo");
        try {
            deptInfo = (DeptInfo) this.getRedisCache(this.id, key);
        } catch (Exception ignored) {
            deptInfo = null;
        }
        if (!Optional.ofNullable(deptInfo).isPresent()) {
            String response = requestData(url, params);
            deptInfo = JSONObject.parseObject(response, DeptInfo.class);
            this.setRedisCache(id, key, deptInfo, expire);
        }
        return deptInfo;
    }

    public List<String> getDeptByParentId(String parentId, String tenantId) {
        String url = buildUrl("/rpc/dept/info/deptIdByParentId");
        Map<String, Object> params = new HashMap<>();
        params.put("parentId", parentId);
        params.put("tenantId", tenantId);

        String response = requestData(url, params);
        return JSONObject.parseArray(response, String.class);
    }

    public List<DeptInfo> getAllDeptByParentId(String deptId, String tenantId) {
        String url = buildUrl("/rpc/dept/info/listBy");
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("currentId", deptId);

        String response = requestData(url, params);
        return JSONObject.parseArray(response, DeptInfo.class);
    }

    public DeptInfo loadDeptByCode(String code) {
        String url = buildUrl("/rpc/dept/info/load");
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        String response = requestData(url, params);
        return JSONObject.parseObject(response, DeptInfo.class);
    }

    public String loadDeptIdByName(String name, String tenantId) {
        String url = buildUrl("/rpc/dept/get/byName");
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("tenantId", tenantId);
        return requestData(url, params);
    }

    public DeptInfoTree subDeptInfo(String deptId, String tenantId) {
        String url = buildUrl("/rpc/dept/sub/info");
        Map<String, Object> params = new HashMap<>();
        params.put("currentId", deptId);
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseObject(response, DeptInfoTree.class);
    }

    public List<UserInfo> listByName(String name, String tenantId) {
        String url = buildUrl("/rpc/user/info/query");
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("tenantId", tenantId);

        String response = requestData(url, params);
        return JSONObject.parseArray(response, UserInfo.class);
    }

    public List<UserInfo> listUserAll(String name, String tenantId) {
        String url = buildUrl("/rpc/user/info/listAll");
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("tenantId", tenantId);

        String response = requestData(url, params);
        return JSONObject.parseArray(response, UserInfo.class);
    }

    public List<DeptUserTree> userMixTree(String name, String tenantId) {
        String url = buildUrl("/rpc/dept/user/mixTree");
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, DeptUserTree.class);
    }


    public String getUserName(String id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", id);
        String url = buildUrl("/rpc/user/info/getNameById");
        String response = requestData(url, map).replaceAll("\"", "");
        return response;
    }

    /**
     * 删除文件引用
     */
    public void deleteByQuotId(String systemQuotId) {
        String url = buildUrl("/rpc/base/quto/delete");
        Map<String, Object> params = new HashMap<>();
        params.put("systemQuotId", systemQuotId);
        requestData(url, params);
    }

    public List<String> getParentIdsById(String deptId) {
        String url = buildUrl("/rpc/dept/parentIds");
        Map<String, Object> params = new HashMap<>();
        params.put("id", deptId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, String.class);
    }

    public List<String> findById(String deptId) {
        String url = buildUrl("/rpc/dept/parentIds");
        Map<String, Object> params = new HashMap<>();
        params.put("id", deptId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, String.class);
    }

    public List<String> getUserIdsByDeptId(String deptId, String tenantId) {
        String url = buildUrl("/rpc/user/info/getUserIdsByDeptId");
        Map<String, Object> params = new HashMap<>();
        params.put("deptId", deptId);
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        List<String> userIds = JSONObject.parseArray(response, String.class);
        return userIds;
    }

    public List<DeptInfoTree> myListDept(String currentId, String tenantId, List<String> dataIds) {
        String url = buildUrl("/rpc/dept/user/myTree");
        Map<String, Object> params = new HashMap<>();
        params.put("currentId", currentId);
        params.put("tenantId", tenantId);
        params.put("deptIds", dataIds);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, DeptInfoTree.class);
    }

    public List<String> getDeptByParentIds(List<String> ids, String tenantId) {
        String url = buildUrl("/rpc/dept/info/getDeptByParentId");
        Map<String, Object> params = new HashMap<>();
        params.put("deptIds", ids);
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, String.class);
    }

    public List<String> getAllDepartments(String deptId, String tenantId) {
        String url = buildUrl("/rpc/dept/info/getAllDepartments");
        Map<String, Object> params = new HashMap<>();
        params.put("deptId", deptId);
        params.put("tenantId", tenantId);
        String response = requestData(url, params);
        return JSONObject.parseArray(response, String.class);
    }

    public String seeKnowBaseFile(String fileId) {
        String url = buildUrl("/rpc/base/info/seeFile");
        Map<String, Object> params = new HashMap<>();
        params.put("fileId", fileId);
        String s = requestData(url, params);
        return JSONObject.parseObject(s, String.class);
    }

    public String downKnowBaseFile(String fileId) {
        String url = buildUrl("/rpc/base/info/downFile");
        Map<String, Object> params = new HashMap<>();
        params.put("fileId", fileId);
        String s = requestData(url, params);
        return JSONObject.parseObject(s, String.class);
    }

    public UserInfo getByPhone(String phone) {
        UserQparams param = new UserQparams();
        param.setPageNo(1);
        param.setPageSize(1);
        param.setPhone(phone);
        IPage<UserInfo> userInfoIPage = this.pageList(param);
        if (userInfoIPage.getTotal() < 1) {
            return null;
        }
        return userInfoIPage.getRecords().get(0);
    }
}
